var localDB = require('nedb');
var app = require('electron').remote;
const appPath = app.app.getPath('appData') + '\\Requester';

var formatDoc = function (doc) {
    if ((typeof doc == 'object') && doc.constructor == Object) {
        var data = doc;
        data.id = doc._id;
        // data.createdAt = doc.createdAt.getTime();
        // data.updatedAt = doc.updatedAt.getTime();
        delete data.createdAt;
        delete data.updatedAt;
        delete data._id;
        return data;
    } else {
        return doc;
    };
};
// 格式化多行数据
var formatDocs = function (docs) {
    var _array = [];
    for (let i = 0; i < docs.length; i++) {
        const item = formatDoc(docs[i]);
        _array.push(item);
    };
    return _array;
};
var Content = function (options) {
    this.db = new localDB({
        filename: appPath + '/userDB/' + options.PorjectName + '_Note' + '.db',
        autoload: true,
        timestampData: true,
    });
    this.openEvent = function () { };
    setTimeout(() => {
        this.openEvent();
    }, 10);
};
Content.prototype.onOpen = function (event) {
    this.openEvent = event;
};
Content.prototype.creat = function (data, cb) {
    this.db.insert({
        title: data.title,
        parentId: data.parentId,
        description: data.description,
        type: data.type,
        images: data.images,
        time: data.time,
        interface: data.interface,
        subset: data.subset,
        disable: false,
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, formatDoc(doc));
        };
    });
};
Content.prototype.upDate = function (id, data, cb) {
    this.db.update({ _id: id }, {
        $set: {
            title: data.title,
            parentId: data.parentId,
            description: data.description,
            type: data.type,
            images: data.images,
            time: data.time,
            interface: data.interface,
            subset: data.subset,
            disable: false,
        }
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, doc);
        };
    });
};
Content.prototype.getAll = function (id, cb) {
    if (id) {
        var query = { type: 'subset', parentId: id, disable: false, };
    } else {
        var query = { type: 'main', disable: false, };
    };
    this.db.find(query).sort({ time: 1 }).exec(function (err, docs) {
        if (err) {
            cb(error, null);
        } else {
            cb(false, formatDocs(docs));
        };
    });
};
Content.prototype.delete = function (id, cb) {
    this.db.update({ _id: id }, {
        $set: {
            disable: true,
        }
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, doc);
        };
    });
};

var Images = function (options) {
    this.db = new localDB({
        filename: './userDB/' + options.PorjectName + '_Image' + '.db',
        autoload: true,
        timestampData: true,
    });
    this.openEvent = function () { };
    setTimeout(() => {
        this.openEvent();
    }, 10);
};
Images.prototype.onOpen = function (event) {
    this.openEvent = event;
};

Images.prototype.creat = function (data, cb) {
    this.db.insert({
        base64: data,
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, formatDoc(doc));
        };
    });
};


Images.prototype.creatByArray = function (_array, cb) {
    if (_array.length == 0) {
        cb(false, []);
        return;
    };
    var index = 0;
    var data = [];
    var CreatEvent = () => {
        this.creat(_array[index].data, (error, doc) => {
            if (error) {
                cb(error, null);
            } else {
                var _data = {
                    title: _array[index].title,
                    id: doc.id,
                };
                data.push(_data);
                if (index >= _array.length - 1) {
                    cb(false, data);
                } else {
                    index++;
                    CreatEvent();
                }
            };
        });
    };
    CreatEvent();
};
Images.prototype.delete = function (id, cb) {
    this.db.remove({ _id: id }, {}, function (err, numRemoved) {
        if (err) {
            cb(err);
        } else {
            cb(false);
        };
    });
};
Images.prototype.deleteByArray = function (_array, cb) {
    if (_array.length == 0) {
        cb(false, []);
        return;
    };
    var index = 0;
    var deleteEvent = () => {
        this.delete(_array[index], (error) => {
            if (error) {
                cb(error, null);
            } else {
                if (index >= _array.length - 1) {
                    cb(false, []);
                } else {
                    index++;
                    deleteEvent();
                }
            };
        });
    };
    deleteEvent();
};
Images.prototype.get = function (id, cb) {
    this.db.findOne({
        _id: id
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            if (doc) {
                cb(false, formatDoc(doc));
            } else {
                cb('获取图片失败,已经删除');
            };
        };
    });
};
module.exports = {
    Content: function (options) {
        return new Content(options);
    },
    Image: function (options) {
        return new Images(options);
    }
};
